package com.example.project.activity.mingxi;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.os.Bundle;

import android.view.View;
import android.widget.AdapterView;
import android.widget.DatePicker;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import androidx.appcompat.app.AppCompatActivity;

import com.android.volley.VolleyError;
import com.example.project.MyApplication;
import com.example.project.R;
import com.example.project.activity.kaishi.LoginActivity;
import com.example.project.adapter.YearBillAdapter;
import com.example.project.bean.ChartItemBean;
import com.example.project.bean.YearDetail;
import com.example.project.utils.YearPickerDialog;
import com.example.project.volley.ConstantUtil;
import com.example.project.volley.Params;
import com.example.project.volley.VolleyInterface;
import com.example.project.volley.VolleyRequest;

import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
//年详情页面
public class HistoryActivity extends AppCompatActivity implements View.OnClickListener {
    ListView historyLv;
    TextView tvYuer,tvIn,tvOut,tvYearTime; //余额，收入，支出，年份
    List<YearDetail> mDatas = new ArrayList<>();
    YearBillAdapter adapter;
    int year,month; //年，月
    int mainId; //用户ID
    Calendar calendar; //日历控件

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView( R.layout.activity_history);
        init();
        initTime();
        MonthInfo();
    }

    //实例化
    private void init() {
        tvYuer=findViewById(R.id.tv_yuer);
        tvIn=findViewById(R.id.tv_in);
        tvOut=findViewById(R.id.tv_out);
        tvYearTime=findViewById(R.id.tv_year_time);
        tvYearTime.setOnClickListener(this);

        mainId= MyApplication.getMainId();
        if (mainId==0){
            AlertDialog alertDialog2 = new AlertDialog.Builder(HistoryActivity.this)
                    .setTitle("警告")
                    .setMessage("你还未登录")
                    .setIcon(R.drawable.jg)
                    .setPositiveButton("取消", new DialogInterface.OnClickListener() {//添加"Yes"按钮
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            finish();
                        }
                    })

                    .setNegativeButton("登录", new DialogInterface.OnClickListener() {//添加取消
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            Intent intent=new Intent( HistoryActivity.this, LoginActivity.class );
                            startActivity( intent );
                        }
                    })
                    .create();
            alertDialog2.show();
        }

        historyLv = findViewById( R.id.history_lv);

        // 设置适配器
        adapter = new YearBillAdapter(this,mDatas);
        historyLv.setAdapter(adapter);
    }

    //获取当前时间
    private void initTime() {
        calendar = Calendar.getInstance();
        year = calendar.get(Calendar.YEAR);
        tvYearTime.setText(year+"年▼");
        volleyYear(year+"","",mainId+"");
        volleyYearList(year+"",mainId+"");
    }


    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.history_iv_back:
                finish();
                break;
            case R.id.tv_year_time:
                selectYearTime();
                break;
        }
    }

    //显示年份框
    private void selectYearTime() {
        new YearPickerDialog(HistoryActivity.this, AlertDialog.THEME_HOLO_LIGHT, new DatePickerDialog.OnDateSetListener() {
            @Override
            public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
                calendar.set(Calendar.YEAR, year);
                String mainIds=String.valueOf( mainId );
                String time =year+"年▼";
                tvYearTime.setText(time);
                volleyYear(year+"","",mainId+"");
                volleyYearList(year+"",mainId+"");
                tvYearTime.setText(time);
            }
        }, calendar.get(Calendar.YEAR), calendar.get(Calendar.MONTH), calendar.get(Calendar.DATE)).show();
    }


    /* 统计某年的总收支情况数据 （记账总钱数）*/
    private void volleyYear(String year,String month,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.MONTHSR, "MONTHInfo", Params.MonthList(year,month,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) {
                System.out.println("数据:"+jsonStr);
                JSONObject jsonObject = null;
                try {
                    jsonObject =new JSONObject( jsonStr );
                    String inMoney=jsonObject.getString( "inMoney" );
                    String outMoney=jsonObject.getString( "outMoney" );
                    float yearmoney=Float.parseFloat(inMoney)-Float.parseFloat(outMoney);
                    DecimalFormat format=new DecimalFormat("#.##");
                    String numberStr = format.format(yearmoney);
                    tvYuer.setText(numberStr);
                    tvIn.setText(inMoney);
                    tvOut.setText(outMoney);
                } catch (JSONException e) {
                    e.printStackTrace();
                }

            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(HistoryActivity.this, "获取信息失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    //查询年里的月的信息
    private void volleyYearList(String year,String mainId) {
        VolleyInterface vif=null;
        VolleyRequest.RequesetPost( ConstantUtil.SelectYear, "SelectYear", Params.GetString2(year,mainId),new VolleyInterface( this ){
            @Override
            public void onMySuccess(String jsonStr) throws JSONException {
                System.out.println( "--------------------------:"+jsonStr.length() );
                JSONArray jsonArray = null;
                // 初始化list数组对象
                ArrayList<YearDetail> list = new ArrayList<>();
                JSONObject json = new JSONObject(jsonStr);
                jsonArray = json.getJSONArray("data");
                for (int i = 0; i < jsonArray.length(); i++) {
                    JSONObject juser = jsonArray.getJSONObject(i);
                    YearDetail yearDetail = new YearDetail();
                    yearDetail.setMonth(Integer.parseInt(juser.getString("month")));
                    yearDetail.setInmoney(Float.parseFloat(juser.getString("inmoney")));
                    yearDetail.setOutmoney(Float.parseFloat(juser.getString("outmoney")));
                    DecimalFormat format=new DecimalFormat("#.##");
                    String numberStr = format.format(Float.parseFloat(juser.getString("yuer")));
                    yearDetail.setYuer(Float.parseFloat(numberStr));

                    list.add(yearDetail);
                    mDatas.clear(); //清除列表
                    mDatas.addAll(list); //添加列表
                    adapter.notifyDataSetChanged(); //刷新
                }
            }

            @Override
            public void onMyError(VolleyError error) {
                Toast.makeText(HistoryActivity.this, "失败", Toast.LENGTH_LONG).show();
            }
            @Override
            public void onImageSuccess(Bitmap bitmap) {

            }
        });
    }

    //跳转当月详情页面
    private void MonthInfo(){
        historyLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                YearDetail yearDetail = mDatas.get(position);  //获取正在被点击的这条信息
                month=yearDetail.getMonth();
                Intent intent=new Intent(HistoryActivity.this,MonthInfoActivity.class);
                intent.putExtra("month",month+"");
                intent.putExtra("year",year+"");
                startActivity(intent);
            }
        });
    }

}
